/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anism.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.anism.API.HolidayPlanningLocal;
import org.anism.business.Planning;
import org.anism.entity.Employee;
import org.anism.entity.HolidayRequest;

/**
 *
 * @author tgqm5519
 */
@WebServlet(name = "DisplayPlanningServlet", urlPatterns = {"/DisplayPlanningServlet"})
public class DisplayPlanningServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        boolean isAuthenticated = false;
        boolean hasFailedLogin = false;
        Employee emp = null;
        HolidayPlanningLocal holidayPlanning = null;

        // Lookup HolidayInput session bean
        try {
            Context jndiContext = new InitialContext();
            holidayPlanning = (HolidayPlanningLocal) jndiContext.lookup("java:global/Holidays2-war/HolidayPlanning!org.anism.API.HolidayPlanningLocal");
        } catch (NamingException ex) {
            Logger.getLogger(DisplayPlanningServlet.class.getName()).log(Level.SEVERE, "Unable to lookup session bean", ex);
        }

        // Check if user is logged in
        if (request.getSession(true).getAttribute("user.authenticated") != null) {
            isAuthenticated = true;
        } else {
            String login = request.getParameter("login");
            String password = request.getParameter("password");

            // Check if user has completed the  authentication form
            if (login != null && password != null) {
                emp = holidayPlanning.authenticate(login, password);

                if (emp != null) {
                    request.getSession().setAttribute("user.authenticated", true);
                    request.getSession().setAttribute("user.firstname", emp.getFirstName());
                    request.getSession().setAttribute("user.lastname", emp.getLastName());
                    request.getSession().setAttribute("user.id", emp.getEmployeeId());
                    isAuthenticated = true;
                } else {
                    hasFailedLogin = true;
                }
            }
        }

        if (!isAuthenticated) { // user is not logged in, display authentication form
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Authentication</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Authentication</h1>");

                if (hasFailedLogin) {
                    out.println("<p>Authentication failed, please try again</p>");
                }
                out.println("<form action=\"./DisplayPlanningServlet\" method=\"post\" >");
                out.println("Login : <input type=\"text\" name=\"login\"/><br />");
                out.println("Password : <input type=\"text\" name=\"password\" /><br />");
                out.println("<input type=\"submit\" value=\"Submit\" />");
                out.println("</form>");
                out.println("<p><a href=\"index.jsp\" >Go back to menu</a></p>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        } else { // user is authenticated
            String employeeId = (String) request.getSession().getAttribute("user.id");
            Planning planning = null;

            if (employeeId != null) {
                planning = holidayPlanning.getPlanning(employeeId);
            }

            // TODO : manage POST parameters

            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Planning</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<p>You are logged in as "
                        + request.getSession().getAttribute("user.id")
                        + " - <a href=\"signout.jsp\" >sign out</a>"
                        + "</p>");
                out.println("<h1>Planning</h1>");
                out.println("<ul>");

                if (planning != null) {
                    for (HolidayRequest hr : planning.getRequestsToDisplay()) {
                        out.println("<li>");
                        // Display request
                        out.println("Start date : " + hr.getStartDate());
                        out.println(" ; End date :  " + hr.getEndDate());
                        out.println(" ; Status : " + hr.getCurrentStatus());
                        out.println("</li>");
                        
                    }
                }

                out.println("</ul>");
                out.println("<p><a href=\"index.jsp\" >Go back to menu</a></p>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
